package user.controllers;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import user.models.ArticleModel;
import user.models.CategoryModel;
import entities.Article;
import entities.Category;
import entities.User;

public class ArticlePreviewServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String param = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		String[] params = param.split("/");
		
		String id = params[0];
		String authKey = "";
		if (params.length > 1) {
			authKey = params[1];
		}
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = (Article) articleModel.getArticle(id);
		
		if (article == null || !article.getAuthKey().equals(authKey)) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		Category category = categoryModel.getCategory(article.getCategory());
		
		//Get User
		User user = (User) request.getAttribute("user_logged_in");
		
		request.setAttribute("article", article);
		request.setAttribute("category", category);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/user/pages/article_preview.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
		
	}
}
